from django.shortcuts import render
from dvadmin.utils.viewset import CustomModelViewSet
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from rest_framework.response import Response
from django.db.models import Q
from .models import ProductionPlan
from .serializers import ProductionPlanSerializer, ProductionPlanCreateUpdateSerializer

# Create your views here.

class ProductionPlanViewSet(CustomModelViewSet):
    """
    生产计划管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = ProductionPlan.objects.all()
    serializer_class = ProductionPlanSerializer
    create_serializer_class = ProductionPlanCreateUpdateSerializer
    update_serializer_class = ProductionPlanCreateUpdateSerializer
    filter_fields = ['status']
    permission_classes = [IsAuthenticated]
    ordering = '-create_datetime'
    search_fields = ['plan_name', 'product']
    extra_filter_backends = []

    def get_queryset(self):
        queryset = super().get_queryset()
        
        # 获取查询参数
        plan_name = self.request.query_params.get('plan_name', None)
        product = self.request.query_params.get('product', None)
        start_date = self.request.query_params.get('start_date', None)
        end_date = self.request.query_params.get('end_date', None)
        
        # 应用模糊搜索
        if plan_name:
            queryset = queryset.filter(plan_name__icontains=plan_name)
        if product:
            queryset = queryset.filter(product__icontains=product)
        
        # 改进日期过滤逻辑
        if start_date:
            queryset = queryset.filter(start_date__gte=start_date)
        if end_date:
            queryset = queryset.filter(end_date__lte=end_date)
            
        return queryset

    def perform_create(self, serializer):
        serializer.save(creator=self.request.user.username)
        
    def perform_update(self, serializer):
        serializer.save(modifier=self.request.user.username)
